package com.vehiclesecure.service;

import com.vehiclesecure.model.User;
import com.vehiclesecure.model.Vehicle;
import com.vehiclesecure.repository.UserRepository;
import com.vehiclesecure.repository.VehicleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * 车辆用户同步服务
 * 用于同步车辆和用户之间的关联关系
 * 当车辆没有对应用户时自动创建用户
 */
@Service
public class VehicleUserSyncService {

    private final VehicleRepository vehicleRepository;
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    @Autowired
    public VehicleUserSyncService(VehicleRepository vehicleRepository,
                                  UserRepository userRepository,
                                  UserService userService,
                                  PasswordEncoder passwordEncoder) {
        this.vehicleRepository = vehicleRepository;
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

    /**
     * 同步所有车辆的用户关联
     * 遍历所有车辆，检查是否有对应的用户，没有则创建
     */
    @Transactional
    public void syncAllVehicleUsers() {
        List<Vehicle> allVehicles = vehicleRepository.findAll();
        System.out.println("开始同步车辆用户关联，共发现 " + allVehicles.size() + " 辆车");

        int createdUsers = 0;
        int updatedVehicles = 0;

        for (Vehicle vehicle : allVehicles) {
            boolean result = syncVehicleUser(vehicle);
            if (result) {
                createdUsers++;
                updatedVehicles++;
            }
        }

        System.out.println("同步完成：新建用户 " + createdUsers + " 个，更新车辆 " + updatedVehicles + " 个");
    }

    /**
     * 同步单个车辆的用户关联
     * @param vehicle 车辆对象
     * @return 是否创建了新用户
     */
    @Transactional
    public boolean syncVehicleUser(Vehicle vehicle) {
        // 如果车辆已经有ownerId，检查用户是否存在
        if (vehicle.getOwnerId() != null && !vehicle.getOwnerId().isEmpty()) {
            Optional<User> existingUser = userRepository.findById(vehicle.getOwnerId());
            if (existingUser.isPresent()) {
                // 用户存在，同步用户信息
                syncUserInfoFromVehicle(existingUser.get(), vehicle);
                return false;
            }
        }

        // 如果车辆有邮箱，检查是否已存在用户
        if (vehicle.getOwnerEmail() != null && !vehicle.getOwnerEmail().isEmpty()) {
            Optional<User> existingUser = userRepository.findByEmail(vehicle.getOwnerEmail());
            if (existingUser.isPresent()) {
                // 用户已存在，建立关联
                User user = existingUser.get();
                vehicle.setOwnerId(user.getId());
                vehicle.setOwnerName(user.getFirstName() + " " + user.getLastName());
                vehicleRepository.save(vehicle);
                return false;
            }
        }

        // 创建新用户
        User newUser = createUserFromVehicle(vehicle);
        vehicle.setOwnerId(newUser.getId());
        vehicle.setOwnerName(newUser.getFirstName() + " " + newUser.getLastName());
        vehicle.setOwnerEmail(newUser.getEmail());
        vehicleRepository.save(vehicle);

        return true;
    }

    /**
     * 根据车辆信息创建用户
     * @param vehicle 车辆对象
     * @return 创建的用户
     */
    private User createUserFromVehicle(Vehicle vehicle) {
        User user = new User();
        
        // 使用邮箱作为用户名，如果没有邮箱则生成一个
        String email;
        if (vehicle.getOwnerEmail() != null && !vehicle.getOwnerEmail().isEmpty()) {
            email = vehicle.getOwnerEmail();
        } else {
            // 生成基于车牌号的邮箱
            String plate = vehicle.getLicensePlate() != null ? 
                          vehicle.getLicensePlate().replaceAll("[^a-zA-Z0-9]", "") : 
                          UUID.randomUUID().toString().substring(0, 8);
            email = "user_" + plate.toLowerCase() + "@vehiclesecure.com";
        }

        // 设置用户名（从车主姓名或车牌号）
        String firstName;
        String lastName;
        if (vehicle.getOwnerName() != null && !vehicle.getOwnerName().isEmpty()) {
            String[] nameParts = vehicle.getOwnerName().split("\\s+", 2);
            if (nameParts.length >= 2) {
                firstName = nameParts[0];
                lastName = nameParts[1];
            } else {
                firstName = vehicle.getOwnerName();
                lastName = "用户";
            }
        } else {
            // 使用车牌号作为姓名
            firstName = vehicle.getLicensePlate() != null ? vehicle.getLicensePlate() : "用户";
            lastName = "车主";
        }

        user.setEmail(email);
        user.setPassword(passwordEncoder.encode("12345678")); // 默认密码
        user.setFirstName(firstName);
        user.setLastName(lastName);
        user.setRole(User.Role.USER);
        user.setVehicleIds(List.of(vehicle.getId())); // 绑定车辆

        return userRepository.save(user);
    }

    /**
     * 同步用户信息从车辆信息
     * @param user 用户对象
     * @param vehicle 车辆对象
     */
    private void syncUserInfoFromVehicle(User user, Vehicle vehicle) {
        // 如果车辆信息有更新，同步到用户信息
        if (vehicle.getOwnerName() != null && !vehicle.getOwnerName().isEmpty()) {
            String[] nameParts = vehicle.getOwnerName().split("\\s+", 2);
            if (nameParts.length >= 2) {
                user.setFirstName(nameParts[0]);
                user.setLastName(nameParts[1]);
            } else {
                user.setFirstName(vehicle.getOwnerName());
                user.setLastName("用户");
            }
        }

        if (vehicle.getOwnerEmail() != null && !vehicle.getOwnerEmail().isEmpty()) {
            user.setEmail(vehicle.getOwnerEmail());
        }

        userRepository.save(user);
    }

    /**
     * 根据邮箱查找或创建用户
     * @param email 邮箱地址
     * @param vehicle 关联的车辆
     * @return 用户对象
     */
    @Transactional
    public User findOrCreateUserByEmail(String email, Vehicle vehicle) {
        Optional<User> existingUser = userRepository.findByEmail(email);
        if (existingUser.isPresent()) {
            return existingUser.get();
        }

        // 创建新用户
        User newUser = new User();
        newUser.setEmail(email);
        newUser.setPassword(passwordEncoder.encode("12345678"));
        newUser.setFirstName("用户");
        newUser.setLastName("车主");
        newUser.setRole(User.Role.USER);
        newUser.setVehicleIds(List.of(vehicle.getId()));

        return userRepository.save(newUser);
    }

    /**
     * 检查并修复所有孤立车辆（没有ownerId的车辆）
     */
    @Transactional
    public void fixOrphanedVehicles() {
        List<Vehicle> orphanedVehicles = vehicleRepository.findByOwnerId(null);
        System.out.println("发现 " + orphanedVehicles.size() + " 辆孤立车辆");

        for (Vehicle vehicle : orphanedVehicles) {
            syncVehicleUser(vehicle);
        }
    }
}